<?php

/**
 * Application model for CakePHP.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class ModuleSmsAccount extends AppModel {

    public $useDbConfig = "organisations";
    public $belongsTo = array(
        'Organisation' => array(
            'className' => 'Organisation',
            'foreignKey' => 'organisation_id',
            'dependent' => false
        )
    );
    public $hasMany = array(
        'ModuleSmsBroadcastList' => array(
            'className' => 'ModuleSmsBroadcastList',
            'foreignKey' => 'module_sms_account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ModuleSmsAccountBroadcast' => array(
            'className' => 'ModuleSmsAccountBroadcast',
            'foreignKey' => 'module_sms_account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ModuleSmsAccountInstantMessage' => array(
            'className' => 'ModuleSmsAccountInstantMessage',
            'foreignKey' => 'module_sms_account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public function populateDefault($organisation_id) {
        // determine if an account already exists
        $exists = $this->find('first', array(
            'conditions' => array(
                'ModuleSmsAccount.organisation_id' => $organisation_id
            ),
            'recursive' => -1
        ));

        // create a new one if one does not already exist
        if (!$exists) {
            $data = array(
                'organisation_id' => $organisation_id,
                'account_balance' => 0,
                'active' => 1
            );

            $this->save($data);

            return array('module_sms_account_id' => $this->id);
        }

        return array('module_sms_account_id' => $exists['ModuleSmsAccount']['id']);
    }

    public function getAccount($organisation_id) {
        return $this->find('first', array(
            'conditions' => array(
                'ModuleSmsAccount.organisation_id' => $organisation_id,
                'ModuleSmsAccount.active' => 1
            )
        ));
    }
    
    public function getAccountById($account_id) {
        return $this->find('first', array(
            'conditions' => array(
                'ModuleSmsAccount.id' => $account_id,
                'ModuleSmsAccount.active' => 1
            )
        ));
    }
    
    public function getPredefinedLists($organisation_id) {
        $categories = ClassRegistry::init('OrganisationMemberCategory')->getCategories($organisation_id);
        
        $this->Organisation->id = $organisation_id;
        
        $lists = array(
            array(
                'category_id' => -1,
                'name' => 'Everyone',
                'size' => $this->Organisation->field('organisation_member_count')
            )
        );
        
        foreach($categories as $cat) {
            $lists[] = array(
                'category_id' => $cat['category']['id'],
                'name' => 'All ' . $cat['category']['name'],
                'size' => $cat['category']['member_count']
            );
        }
        
        return $lists;
    }

    public function getBroadcastLists($organisation_id, $include_predefined = false) {
        $conditions = array(
            'ModuleSmsBroadcastList.active' => 1
        );
        
        if( $include_predefined ) {
            $conditions[] = array(
                'or' => array(
                    'ModuleSmsAccount.organisation_id' => $organisation_id,
                    'ModuleSmsBroadcastList.module_sms_account_id' => null
                )
            );
        }
        
        else {
            $conditions['ModuleSmsAccount.organisation_id'] = $organisation_id;
        }
        
        $data = $this->ModuleSmsBroadcastList->find('all', array(
            'fields' => array('id', 'name', 'sender_id', 'type', 'created', 'modified'),
            'conditions' => $conditions,
            'order' => array('ModuleSmsBroadcastList.name')
        ));

        if ($data) {
            $list = array();

            foreach ($data as $d) {
                $list[] = $d['ModuleSmsBroadcastList'];
            }

            return array('status' => 'success', 'lists' => $list);
        }
        
        return array('status' => 'failed', 'message' => 'No broadcast lists found for this account.');
    }
    
    public function getBroadcastListSize($broadcast_list_id) {
        return $this->ModuleSmsBroadcastList->ModuleSmsBroadcastListContact->find('count', array(
            'conditions' => array(
                'ModuleSmsBroadcastListContact.module_sms_broadcast_list_id' => $broadcast_list_id
            )
        ));
    }
    
    public function scheduleBroadcast($module_sms_account_id, $broadcast_list_id, $schedule, $message) {
        $this->ModuleSmsAccountBroadcast->create();
        
        $saved = $this->ModuleSmsAccountBroadcast->save(array(
            'module_sms_account_id' => $module_sms_account_id,
            'module_sms_broadcast_list_id' => $broadcast_list_id,
            'send_at' => $schedule,
            'message' => $message,
            'sent' => 0
        ));
        
        return array('status' => $saved ? 'success' : 'failed', 'message' => $saved ? 'Broadcast Scheduled' : 'Scheduling failed');
    }
    
    public function schedulePredefinedBroadcast($module_sms_account_id, $category_id, $schedule, $message) {
        $this->ModuleSmsAccountBroadcast->create();
        
        $saved = $this->ModuleSmsAccountBroadcast->save(array(
            'module_sms_account_id' => $module_sms_account_id,
            'organisation_member_category_id' => $category_id,
            'send_at' => $schedule,
            'message' => $message,
            'sent' => 0
        ));
        
        return array('status' => $saved ? 'success' : 'failed', 'message' => $saved ? 'Broadcast Scheduled For Predefined List' : 'Scheduling failed');
    }

    /**
     * Returns an array containing the list of contacts for the specified organisation's broadcast list.
     * If no contacts are found, and array with an error message is returned.
     * 
     * @param int $organisation_id
     * @param int $broadcast_list_id
     * @return array
     */
    public function getContactsList($organisation_id, $broadcast_list_id, $limit = 10, $offset = 0) {
        $account = $this->getAccount($organisation_id);
        
        $data = $this->ModuleSmsBroadcastList->ModuleSmsBroadcastListContact->find('all', array(
            'conditions' => array(
                'ModuleSmsBroadcastList.module_sms_account_id' => $account['ModuleSmsAccount']['id'],
                'ModuleSmsBroadcastList.id' => $broadcast_list_id,
                'ModuleSmsBroadcastList.active' => 1,
                'ModuleSmsBroadcastListContact.active' => 1
            ),
            'limits' => $limit,
            'offset' => $offset
        ));
        
        if( $data ) {
            $contacts = array();
            
            foreach($data as $d) {
                $contacts[] = array(
                    'id' => $d['ModuleSmsBroadcastListContact']['id'],
                    'name' => $d['ModuleSmsBroadcastListContact']['name'],
                    'number' => $d['ModuleSmsBroadcastListContact']['number'],
                );
            }
            
            return array('status' => 'success', 'contacts' => $contacts);
        }
        
        return array('status' => 'failed', 'message' => 'No contacts found in the specified broadcast list');
    }
    
    public function getAccountBalance($organisation_id) {
        $account = $this->getAccount($organisation_id);
        
        if( $account ) {
            return $account['ModuleSmsAccount']['account_balance'];
        }
        
        return 0;
    }
    
    public function hasCredit($organisation_id) {
        $account = $this->getAccount($organisation_id);
        
        if( $account ) {
            return $account['ModuleSmsAccount']['account_balance'] > 0;
        }
        
        return false;
    }
    
    public function deductCredit($organisation_id, $credit = 1) {
        $account = $this->getAccount($organisation_id);
        
        if( $account ) {
            $this->updateAll(array('ModuleSmsAccount.account_balance' => $account['ModuleSmsAccount']['account_balance'] - $credit),
                    array('ModuleSmsAccount.organisation_id' => $organisation_id));
        }
    }
    
    public function addCredit($organisation_id, $credit) {
        $account = $this->getAccount($organisation_id);
        
        if( $account ) {
            $this->updateAll(array('ModuleSmsAccount.account_balance' => $account['ModuleSmsAccount']['account_balance'] + $credit ),
                    array('ModuleSmsAccount.organisation_id' => $organisation_id));
        }
    }
}
 